const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser')
const logger = require('morgan');
const app = express();

let RespFmt = require('./utils/RespFmt')
let indexRouter = require('./routes/index');
let usersRouter = require('./routes/users');
let newsRouter = require('./routes/news')

let limiter = require('./middleWare/rateLimit.middleware')

// view engine setup
app.engine('html', require('express-art-template'))
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(bodyParser.json())
// 控制访问频率

app.use(limiter)
// app.use(function (req, res, next) {
//     console.log(res.render('news/oftenVisits.html',{}))
//     next()
// })

// let staticPath = []
app.use('/', express.static(path.join(__dirname, 'template')));
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/static', express.static(path.join(__dirname, 'static')));

/**
 * cacheController.getHTMLtoCache  在news路由中
 */
app.use('/', newsRouter);

app.use('/tbk', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler

app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    req.app.locals.message = err.message;
    req.app.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('404.ejs', {req, res: RespFmt.faild(JSON.stringify(err))});
});

module.exports = app;
